package com.gs.api.project.video.web;

import com.gs.api.project.video.entity.ParseParam;
import com.gs.api.util.http.HttpUtilDown;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Map;

/**
 * @author guoyunfei on 2021/12/5 22:51
 * @className ForwardController
 * @description TODO
 * @Version 1.0
 * 源码联系微信：2549789059
 */
@RestController
@RequestMapping("{appid}/down")
public class DownFileController {


    @RequestMapping(value = "image")
    public ResponseEntity<Resource> forward(@RequestParam(name = "url", required = true) String url) {
        System.out.println("Start: ------------------------->");

        Resource resource = null;

        InputStream inputStream;
        try {
            inputStream = new URL(url).openStream();

            resource = new ByteArrayResource(toByteArray(inputStream));
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }

        return ResponseEntity.ok().contentType(MediaType.IMAGE_PNG)
                .header(HttpHeaders.CONTENT_DISPOSITION, " filename=\"" + getFileName(url) + "\"")
                .body(resource);

    }


    @RequestMapping(value = "fileGet")
    public void fileGet(ParseParam parseParam, HttpServletResponse response, HttpServletRequest request) throws UnsupportedEncodingException {

        parseParam.setUrl(getParams(request));

        int i = parseParam.getUrl().lastIndexOf("/");
        String fileName = parseParam.getUrl().substring(i+1);
        HttpUtilDown.download(response,parseParam.getUrl(), fileName);
    }


    private byte[] toByteArray(InputStream in) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            byte[] bytes = new byte[1024];
            int n;
            while ((n = in.read(bytes)) != -1) {
                byteArrayOutputStream.write(bytes, 0, n);
            }
            System.out.println(byteArrayOutputStream.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return byteArrayOutputStream.toByteArray();

    }

    private String getFileName(String url) {
        String[] strs = url.split("/");
        for (String str : strs) {
            // 这里我仅处理png格式的，根据需求修改即可
            if (str.toLowerCase().endsWith(".png") || str.toLowerCase().endsWith(".jpeg")
                    || str.toLowerCase().endsWith(".jpg") || str.toLowerCase().endsWith(".gif")
                    || str.toLowerCase().endsWith(".webp") || str.toLowerCase().endsWith(".mp4")) {
                return str;
            }
        }
        return null;
    }

    /**
     * 获取请求参数
     * @param request
     * @return
     */
    private String getParams(HttpServletRequest request) throws UnsupportedEncodingException {

        Map<String, String[]> parameterMap = request.getParameterMap();

        String url = "";

        for(String s : parameterMap.keySet()){

            String[] values = parameterMap.get(s);

            if(StringUtils.isNotBlank(url)){
                //处理请求参数传递编码问题
                String encode = URLEncoder.encode(values[0], "UTF-8");
                //URLDecoder.decode(strUri, "UTF-8");

                url+="&"+s+"="+encode;
            }else{
                url = values[0];
            }
        }
        return url;
    }

}
